from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options  # 五可视化界面
from selenium.webdriver.support import expected_conditions as EC
from ProjectTool.WebTool.config.conf import DRIVER_PATH
import time
import json


class BaseFunc:
    def __init__(self, http_status, host, port, domain, local_storage, session_storage, driver=None,
                 driver_status=None):
        self.driver_status = driver_status  # 是否使用无界面浏览器
        self.driver = driver  # 浏览器对象
        self.local_storage = local_storage  # 本地存储
        self.session_storage = session_storage  # 会话存储
        self.storage_status = True if driver else False

        self.base_url = domain if domain else '{http_status}://{host}:{port}/'.format(http_status=http_status,
                                                                                      host=host, port=port)

    # 实例化后最开始执行的函数
    def run(self):
        self.get_driver(self.driver)  # 初始化浏览器对象
        self.open(self.page_url)  # 打开对应页面

    # 权限信息写入
    def permission_information(self):
        self.set_local_storage()  # 本地存储
        self.set_session_storage()  # 会话存储

    # 获取浏览器对象
    def get_driver(self, driver):
        if not driver:
            chrome_options = Options()
            chrome_options.add_argument('--headless')
            chrome_options.add_argument('--disable-gpu')
            if self.driver_status:
                driver = webdriver.Chrome(executable_path=DRIVER_PATH, chrome_options=chrome_options)
            else:
                driver = webdriver.Chrome(executable_path=DRIVER_PATH)
            # self.driver.maximize_window()
            self.driver = driver

    # 写入本地存储
    def set_local_storage(self):
        if not self.storage_status:
            self.local_storage = json.loads(self.local_storage) if self.local_storage else self.local_storage
            if isinstance(self.local_storage, dict):
                js_str = "window.localStorage.setItem('{key}','{value}')"
                for key in self.local_storage:
                    vlaue = self.local_storage[key]
                    js_str = js_str.format(key=key,value=json.dumps(vlaue))
                    self.driver.execute_script(js_str)
                self.driver.refresh()

    # 写入会话存储
    def set_session_storage(self):
        if not self.storage_status:
            self.session_storage = json.loads(self.session_storage) if self.session_storage else self.session_storage
            if isinstance(self.session_storage,dict):
                js_str = "window.sessionStorage.setItem('{key}','{value}')"
                for key in self.session_storage:
                    vlaue = self.session_storage[key]
                    js_str = js_str.format(key=key, value=json.dumps(vlaue))
                    self.driver.execute_script(js_str)
                self.driver.refresh()

    # 打开url
    def open(self, page_url):
        self.driver.maximize_window()
        now_url = self.driver.current_url
        new_url = self.base_url + page_url
        if not page_url.find('http://') or not page_url.find('https://'):
            self.driver.get(page_url)
        elif now_url.find(self.base_url):
            self.driver.get(new_url)
        else:
            print('url不合法：{0}'.format(new_url))
            pass

    # 关闭浏览器
    def quit(self):
        self.driver.quit()

    # 获取标签对象
    def find_element(self, loc, timeout=10, poll_frequency=0.5, ignored_exceptions=None):
        element = WebDriverWait(self.driver, timeout, poll_frequency, ignored_exceptions).until(
            EC.presence_of_element_located(loc)  # loc:(By.ID, "kw")
        )
        return element

    # 获取一组元素
    def find_elements(self, loc, timeout=10, poll_frequency=0.5, ignored_exceptions=None):
        elements = WebDriverWait(self.driver, timeout, poll_frequency, ignored_exceptions).until(
            EC.presence_of_all_elements_located(loc)  # loc:(By.ID, "kw")
        )
        return elements

    # 输入内容
    def send_keys(self, element, *args):
        if len(args) == 1 and args[0] is None:
            return
        element.clear()
        element.send_keys(*args)

    # 获取单个文本
    def get_element_text(self, element):
        return element.text

    # 获取一组元素的文本
    def get_elements_text(self, elements):
        return [element.text for element in elements]

    # 直接输入元素获取文本
    def get_text(self, loc):
        element = self.find_element(loc=loc)
        text = element.text
        return text

    # 点击元素
    def click(self, element):
        element.click()
        time.sleep(1)

    # 执行js代码
    def execute_script(self, js_str):
        self.driver.execute_script(js_str)

    # 处理弹出的警告页面   确定
    def accept(self):
        self.driver.switch_to_alert().accept()
        time.sleep(1)

    # 处理弹出的警告页面   取消
    def dismiss(self):
        self.driver.switch_to_alert().dismiss()
        time.sleep(1)

    # 向下拖动一屏的像素
    def drag_down(self, y=None):
        if not y:
            y = 'document.body.scrollHeight'
        self.driver.execute_script('window.scrollTo(0,{y})'.format(y=y))

    # 后退
    def back(self):
        self.driver.back()

    # 前进
    def forward(self):
        self.driver.forward()


if __name__ == '__main__':
    # driver = webdriver.Chrome()
    # a = BaseFunc(driver)
    pass
